package com.dhcc.core.framework.util;

import java.beans.BeanInfo;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.lang.reflect.Method;
import java.util.Map;

import com.dhcc.core.framework.exception.BizException;
import com.google.common.collect.Maps;

/**
 * Bean和Map互转
 * 
 * @ClassName: Bean2MapUtil
 * @Description: TODO
 * @author: cyf
 * @date: 2018年1月2日 上午9:31:12
 */
public class Bean2MapUtil {

    public static Map<String, Object> toMap(Object o) {
        Map<String, Object> values = Maps.newHashMap();
        try {
            BeanInfo info = Introspector.getBeanInfo(o.getClass());
            for (PropertyDescriptor pd : info.getPropertyDescriptors()) {
                Method getter = pd.getReadMethod();
                if (getter != null) {
                    values.put(pd.getName(), getter.invoke(o));
                }
            }
        } catch (Exception e) {
            throw new BizException("bean2map转换错误！");
        }
        return values;
    }

    public static <T> T toObj(Class<T> clazz, Map<?, ?> map) {
        T obj = null;
        try {
            obj = clazz.newInstance();
            BeanInfo beanInfo = Introspector.getBeanInfo(obj.getClass());
            PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();
            for (int i = 0; i < propertyDescriptors.length; i++) {
                PropertyDescriptor descriptor = propertyDescriptors[i];
                String propertyName = descriptor.getName();

                if (map.containsKey(propertyName)) {
                    Object value = map.get(propertyName);
                    Object[] args = new Object[1];
                    args[0] = value;
                    descriptor.getWriteMethod().invoke(obj, args);
                }
            }
        } catch (Exception e) {
            throw new BizException("bean2map转换错误！");
        }
        return obj;
    }

}
